package dawn.jxufe.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author dawn21
 * @version 1.0
 * @date 2022/8/3 20:52
 * @component
 */
@Component // 加入bean
@Aspect // 切面组件
public class ServiceLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    // 定义切入点
    @Pointcut("execution(* dawn.jxufe.community.service.*.*(..))")
    public void pointcut(){
    }

    @Before("pointcut()") // 在 切入点的开始 处理事情，例如：输出、记录日志。
    public void before(JoinPoint joinPoint) { // 连接点，目标组件，要调用的方法。通过它就知道要调用那个类，哪个方法。
        // 用户[ip地址]，在[date]，访问了[class.method()]。
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
        System.out.println("before");
    }
}
